import React, { useState, useEffect, useCallback } from 'react';
import { JsonViewer } from '@textea/json-viewer';
import { Modal, Button } from 'antd';
export default (props) => {
  const { request, title = 'JSON数据', value = {} } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const [data, setData] = useState(null);
  const getData = useCallback(async () => {
    const { code, data } = await request?.();
    if (code === 0 && data) {
      setData(data);
    } else {
      setData(null);
    }
  }, [request]);
  useEffect(() => {
    if (visible && request) {
      getData();
    }
  }, [visible]);
  const onClose = useCallback(() => {
    setVisible(false);
  }, []);
  const onOpen = useCallback(() => {
    setVisible(true);
  }, []);
  return (
    <>
      <Button onClick={onOpen} type="link">
        JSON数据
      </Button>
      {visible ? (
        <Modal onOk={onClose} onCancel={onClose} title={title} open={true}>
          <JsonViewer value={data || value} />
        </Modal>
      ) : null}
    </>
  );
};
